class Solution {
public:
    int countValidSelections(vector<int>& nums) {
        int n = nums.size();
        vector<int> fr(n), ba(n);

        fr[0] = nums[0];
        for (int i = 1; i < n; i++) fr[i] = fr[i - 1] + nums[i];
        ba[n - 1] = nums[n - 1];
        for (int i = n - 2; i >= 0; i--) ba[i] = ba[i + 1] + nums[i];

        int res = 0;
        for (int i = 0; i < n; i++)
            if (nums[i] == 0) {
                int last = i == 0 ? 0 : fr[i - 1];
                int next = i == n - 1 ? 0 : ba[i + 1];
                if (last == next + 1) res += 1;
                else if (last == next - 1) res += 1;
                else if (last == next) res += 2;
            }
        return res;
    }
};